<?php
/**
 * Created by PhpStorm.
 * User: qishengqiang
 * Date: 2022-06-02
 * Time: 14:36
 */

namespace app\applet\controller;


use app\applet\BaseController;
use think\facade\Db;

class OrderController extends BaseController
{
    /**
     * @return \think\response\Json
     */
    public function indexAction()
    {
        try {
            if (!$this->user) {
                throw new \Exception('请先登录', 401);
            }

            $params = $this->request->get();

            $select = [
                'where' => $this->_get_cond($params),
                'order' => [
                    'orderId' => 'desc'
                ]
            ];

            $orders = $this->app->orderService->getLists($select, $this->page);

            $data['lists'] = [];

            if (count($orders)) {
                foreach ($orders as $order) {
                    $data['lists'][] = [
                        'orderId' => $order->orderId,
                        'orderNo' => $order->orderNo,
                        'totalCredit' => $order->totalCredit,
                        'goodsCount' => count($order->orderGoods),
                        'orderStatus' => $order->orderStatus,
                        'orderStatusText' => $order->getOrderStatusText(),
                        'createdAt' => $order->createdAt,
                        'goods' => $this->app->orderService->getGoods($order->orderId)['data']
                    ];
                }
            }

            $data['totalInfo'] = $this->app->utilService->getMeta($orders);

            return json()->data(['code' => 200, 'msg' => '查询成功', 'data' => $data]);
        } catch (\Exception $e) {
            return json()->data(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data' => [],$e->getLine(),$e->getFile()]);
        }
    }

    /**
     * @return \think\response\Json
     */
    public function detailAction()
    {
        try {
            if (!$this->user) {
                throw new \Exception('请先登录', 401);
            }

            $orderNo = $this->request->get('orderNo');

            $order = $this->app->orderService->getDetailByOrderNo($orderNo);

            if (!$order) {
                throw new \Exception('订单不存在');
            }

            $goodsInfo = $this->app->orderService->getGoods($order->orderId);
            $data = [
                'orderId' => $order->orderId,
                'orderNo' => $order->orderNo,
                'totalCredit' => $order->totalCredit,
                'orderStatus' => $order->orderStatus,
                'orderStatusText' => $order->getOrderStatusText(),
                'createdAt' => $order->createdAt,
                'goods' => $goodsInfo['data'],
                'consign' => [
                    'consignee' =>$order->express()->value('consignee'),
                    'phone' => $order->express()->value('phone'),
                    'address'=>$order->express && $order->express()->value('provinceCode')?$order->express->province->provinceName.$order->express->city->cityName.$order->express->area->areaName.$order->express->address:'',
                    'number' => $order->express()->value('number'),
                    'idcard' => $order->express()->value('idcard'),
                    'email' => $order->express()->value('email'),
                ],
                'express' => [
                    'expressNo' => $order->express()->value('expressNo')?:'',
                    'expressCompany' => $order->express()->value('expressCompany')?:'',
                    'expressAt' => $order->express()->value('expressAt')?:'',
                ]
            ];

            return json()->data(['code' => 200, 'msg' => '查询成功', 'data' => $data]);
        } catch (\Exception $e) {
            return json()->data(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    /**
     * @return \think\response\Json
     */
    public function addAction()
    {
        Db::startTrans();

        try {
            if (!$this->user) {
                throw new \Exception('请先登录', 401);
            }

            if(empty($this->post['goodsId'])){
                throw new \Exception("缺少商品参数");
            }

            $goodsNum = isset($this->post['goodsNum'])?$this->post['goodsNum']:1;

            //1. 商品是否存在
            $goods = $this->app->goodsService->getDetail($this->post["goodsId"]);

            //2. 用户积分是否能够支付
            if ($goods->credit && $goods->credit > $this->user->currentCredit) {
                throw new \Exception('积分不足', 500);
            }

            $data = $this->app->orderService->getPreviewOrder($goods, $goodsNum);

            if ($goods['categoryId'] == 2) {
                $address = $this->app->userAddressService->getDetail($this->post['addressId']);

                $consign = isset($this->post['consign'])?$this->post['consign']:[];

            } else {
                $address = [];
                $consign = isset($this->post['consign'])?$this->post['consign']:[];
            }

            if (isset($consign['consignee']) && $consign['consignee'] == '') {
                throw new \Exception('请填写姓名', 500);
            }

            if (isset($consign['phone']) && $consign['phone'] == '') {
                throw new \Exception('请填写手机号', 500);
            }

            if (isset($consign['idcard']) && $consign['idcard'] == '') {
                throw new \Exception('请填写身份证号', 500);
            }

            if (isset($consign['email']) && $consign['email'] == '') {
                throw new \Exception('请填写邮箱', 500);
            }

            if (isset($consign['number']) && $consign['number'] == '' && mb_strlen($consign['number']) != 18) {
                throw new \Exception('请填写18位志愿者编号', 500);
            }

            $order = $this->app->orderService->create($data, $address, $this->user, $this->appletId, $consign);

            $this->app->goodsService->reduceStock($goods, $goodsNum);

            $remark = '兑换'.$data['goods']['goodsName'];
            $this->app->userCreditService->consume($this->user, $data['totalCredit'], $remark);

            Db::commit();

            return json()->data(['code' => 200, 'msg' => '操作成功', 'data' => $order]);

        } catch (\Exception $e) {
            Db::rollback();
            return json()->data(['code' => 500, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    /**
     * 撤销订单
     * @return \think\response\Json
     */
    public function cancelAction()
    {
        Db::startTrans();
        try {
            if (!$this->user) {
                throw new \Exception('请先登录', 401);
            }

            if (!isset($this->post['orderNo'])) {
                throw new \Exception('订单号不存在');
            }

            $order = $this->app->orderService->getDetailByOrderNo($this->post['orderNo']);

            if (!$order) {
                throw new \Exception('订单不存在');
            }

            if ($order->orderStatus != 1) {
                throw new \Exception('订单状态不对');
            }

            $this->app->orderService->cancel($order);

            Db::commit();

            return json()->data(['code' => 200, 'msg' => '操作成功', 'data' => []]);
        } catch (\Exception $e) {
            Db::rollback();
            return json()->data(['code' => 500, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    /**
     * @Post('/preview')
     */
    public function previewAction()
    {
        Db::startTrans();
        try {
            if (!$this->user) {
                throw new \Exception('请先登录', 401);
            }

            $goodsNum = isset($this->post['goodsNum'])?$this->post['goodsNum']:1;

            //1. 商品是否存在
            $goods = $this->app->goodsService->getDetail($this->post["goodsId"]);
            $goods->clickCount += 1;
            $goods->save();

            //2. 用户积分是否能够支付
            if ($goods->credit && $goods->credit > $this->user->currentCredit) {
                throw new \Exception('积分不足', 500);
            }

            $data = $this->app->orderService->getPreviewOrder($goods, $goodsNum);

            $consign = $this->app->userAddressService->getDefaultAddress($this->user);

            if ($goods['categoryId'] == 2 && $consign) {
                $data['consign'] = [
                    'addressId' => $consign->addressId?:'',
                    'consignee' => $consign->consignee?:'',
                    'address'=>$consign->province()->value('provinceName').$consign->city()->value('cityName').$consign->area()->value('areaName').$consign->address?:'',
                    'phone' => $consign->phone?:''
                ];
            } else {
                $data['consign'] = [
                    'addressId' => '',
                    'consignee' => '',
                    'address' => '',
                    'phone' => ''
                ];
            }

            $data['express'] = [
                'expressAmount' => '0.00'
            ];

            Db::commit();

            return json()->data(['code' => 200, 'msg' => '操作成功', 'data' => $data]);

        } catch (\Exception $e) {
            Db::rollback();

            return json()->data(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    /**
     * @return mixed
     * @throws \Exception
     * @Post('/receive')
     */
    public function receiveAction()
    {
        try {
            if (!isset($this->post['orderNo'])) {
                throw new \Exception('订单号不存在');
            }

            $order = $this->app->orderService->getDetailByOrderNo($this->post['orderNo']);

            if (!$order) {
                throw new \Exception('订单不存在');
            }

            if ($order->orderStatus != 2) {
                throw new \Exception('订单未发货');
            }

            $order->orderStatus = 3;
            $order->save();

            if ($order->express) {
                $order->express->expressStatus = 2;
                $order->express->save();
            }

            return json()->data(['code' => 200, 'msg' => '操作成功', 'data' => []]);

        } catch (\Exception $e) {

            return json()->data(['code' => 500, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    public function _get_cond($params)
    {
        $cond = [];

        $cond[] = [
            'userId', '=', $this->user->userId
        ];

        $cond[] = [
            'appletId', '=', $this->appletId
        ];

        if (isset($params['orderStatus']) && $params['orderStatus'] != '') {
            $cond[] = [
                'orderStatus', '=', $params['orderStatus']
            ];
        } else {
            $cond[] = [
                'orderStatus', '>=', 0
            ];
        }

        return $cond;
    }
}